﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SharingCenter.Web.Classes;

namespace SharingCenter.Web.Admin.Posts
{
    public partial class List : AdminPageBase
    {
        Guid _cid = Guid.Empty;
        protected Sc_PostCategory _category;
        protected void Page_Init(object sender, EventArgs e)
        {
            if (Request.QueryString["c"] == null)
            {
                RedirectToDefaultPage();
            }
            else
            {
                try
                {
                    _cid = new Guid(Request.QueryString["c"]);
                    _category = PostOperations.GetCategory(_cid);
                }
                catch { RedirectToDefaultPage(); }
            }

            ListView1.ItemDataBound += new EventHandler<ListViewItemEventArgs>(ListView1_ItemDataBound);
            ListView1.ItemCommand += new EventHandler<ListViewCommandEventArgs>(ListView1_ItemCommand);
        }

        void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            Guid tid = (Guid)ListView1.DataKeys[((ListViewDataItem)e.Item).DataItemIndex].Value;
            switch (e.CommandName)
            {
                case "SetHot":
                    SetHot(tid);
                    break;
                case "CancelHot":
                    SetHot(tid);
                    break;
                case "TopThread":
                    SetRecommend(tid);
                    break;
                case "CancelTopThread":
                    SetRecommend(tid);
                    break;
                case "DeleteThread":
                    Delete(tid);
                    break;
                default: break;
            }
            ListView1.DataBind();
        }

        private void SetRecommend(Guid tid)
        {
            PostOperations.SetRecommendedThread(tid);
        }

        private void Delete(Guid tid)
        {
            PostOperations.DeleteThread(tid);
        }

        private void SetHot(Guid tid)
        {
            PostOperations.SetCancelThreadHot(tid);
        }

        void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            ThreadWithMainPost item = (ThreadWithMainPost)((ListViewDataItem)e.Item).DataItem;
            Panel hotPanel = (Panel)e.Item.FindControl("pnHot");
            int hotByRead = int.Parse(SiteConfig.ReadSetting(SiteConfigSection.Post, "HotThreadByReadCount"));
            int hotByReply = int.Parse(SiteConfig.ReadSetting(SiteConfigSection.Post, "HotThreadByReplyCount"));

            hotPanel.Visible = Convert.ToBoolean(item.IsHot) || hotByRead > 0 && item.ViewCount >= hotByRead || hotByReply > 0 && item.TotalPosts - 1 >= hotByReply;
        }
    }
}
